#pragma once
#include <iostream>
#include <pthread.h>
#include <signal.h>
#include "TcpServer.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"

#define PORT 8080

class HttpServer
{
private:
    int _port;
    TcpServer* _tcp_svr;
    ThreadPool* _thread_pool;
    bool _stop;

public:
    HttpServer(int port = PORT) : _port(port), _tcp_svr(nullptr), _stop(false)
    {}

    void InitServer()
    {
        signal(SIGPIPE, SIG_IGN); // 忽略SIGPIPE信号

        _tcp_svr = TcpServer::GetInstance(_port);
        _thread_pool = ThreadPool::GetInstance();
    }

    void Loop()
    {
        LOG(INFO) << "http sever loop begin\n";
        int listen_sock = _tcp_svr->GetListenSock();

        while (!_stop)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            int sock = accept(listen_sock, (struct sockaddr*)&peer, &len);
            if (sock < 0)
                continue;

            LOG(INFO) << "get a new link ... " << sock << std::endl;

            Task task(sock);
            _thread_pool->PushTask(task);
        }
    }

    ~HttpServer()
    {}

};